package com.atstudent.gmall.product.service.impl;

import com.atstudent.gmall.product.entity.BaseAttrValue;
import com.atstudent.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atstudent.gmall.product.entity.BaseAttrInfo;
import com.atstudent.gmall.product.service.BaseAttrInfoService;
import com.atstudent.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 薛有朋
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2024-11-17 20:40:42
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrInfoService{

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> findBaseAttrInfo(Long c1Id, Long c2Id, Long c3Id) {
        return baseAttrInfoMapper.findBaseAttrInfo(c1Id , c2Id , c3Id);
    }

    @Override
    @Transactional //涉及到多表操作 要开启事务
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {
        //先判断此平台属性在数据库是否存在 看是否有id
        Long attrInfoId = baseAttrInfo.getId();

        if (attrInfoId == null){ //新增
            //保存平台属性
            this.save(baseAttrInfo);

            //保存平台属性值
            saveBaseAttrValue(baseAttrInfo);
        }else { //修改

            //先修改平台属性
            this.updateById(baseAttrInfo);

            //先删除平台属性值 根据平台属性id
            removeBaseAttrValue(attrInfoId);

            //保存平台属性值
            saveBaseAttrValue(baseAttrInfo);
        }

    }

    //删除平台属性值
    public void removeBaseAttrValue(Long attrInfoId){
        LambdaQueryWrapper<BaseAttrValue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseAttrValue::getAttrId , attrInfoId);
        baseAttrValueService.remove(lambdaQueryWrapper);
    }

    //保存平台属性值
    public void saveBaseAttrValue(BaseAttrInfo baseAttrInfo){
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList(); //拿到平台属性值
        List<BaseAttrValue> baseAttrValueList = attrValueList.stream().map(baseAttrValue -> {
            baseAttrValue.setId(null);
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            return baseAttrValue;
        }).collect(Collectors.toList());
        baseAttrValueService.saveBatch(baseAttrValueList);
    }
}




